from aiohttp import web
import aiohttp
import traceback
import re

routes = web.RouteTableDef()
app = web.Application()



@routes.view("/")
class Request(web.View):
    async def get(self):
        url = self.request.query["url"]
        style = self.request.query["style"]
        if style=='login':
            login = True
        else:
            login = False
        print(url)
        try:
            resp = await fetch(url, login)
            if re.match(r".*json.*", resp.get("headers", {})["Content-Type"]) :
                with open("E:\git_project\spidertools\server\pages\json_template.html", "rb") as f:
                    text = f.read().decode() % resp["text"]
            elif re.match(r'.*image.*', resp.get("headers", {})["Content-Type"]):
                with open("E:\git_project\spidertools\server\pages\img_template.html", "rb") as f:
                    text = f.read().decode() % resp["url"]
            else:
                text = resp.get("text")
        except:
            text = traceback.format_exc()
        return web.Response(text=text, headers={"Content-Type": "text/html;charset=utf-8"})

async def no_login_fetch(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            # print(resp.status)
            try:
                text = await resp.text()
            except:
                text = ""
            return {
                "text": text,
                "headers": resp.headers
            }


async def login_fetch(url):
    cookies = {
        "ig_pr": "1",
        "csrftoken": "quJnvtr5G1CNUXG8kST5WQJj7qnmgRMw",
        "sessionid": "39456692709%3Ao2r9KSTX5ow9n2%3A8",
    }
    async with aiohttp.ClientSession(cookies=cookies) as session:
        async with session.get(url) as resp:
            try:
                text = await resp.text()
            except:
                text = ""
            return {
                "text": text,
                "headers": resp.headers,
                "url": resp.url
            }

async def fetch(url, login=False):
    if not login:
        return await no_login_fetch(url)
    return await login_fetch(url)

app.add_routes(routes)
        